﻿using AutoStar.Common;
using AutoStar.Models;
using GalaSoft.MvvmLight.Command;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Linq;
using System.Reflection;
using System.Runtime.Remoting.Channels;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

namespace AutoStar.ViewModel
{
    public class SettingViewVM : BaseViewModel
    {
        public LowTemperatureModule _lowTemperatureModule;
        private CancellationTokenSource _cancellationTokenSource;
        public ObservableCollection<string> ChannelTypes { get; private set; }
        public ObservableCollection<string> Names { get; private set; }
        public ObservableCollection<string> Commands { get; private set; }
        public List<ChannelViewModel> channels { get; set; }
        public SettingViewVM()
        {
            Categories = new ObservableCollection<string>();
            ChannelTypes = new ObservableCollection<string>();
            Names = new ObservableCollection<string>();
            Commands = new ObservableCollection<string>();
            _lowTemperatureModule = new LowTemperatureModule("COM6");
            _cancellationTokenSource = new CancellationTokenSource();
        }

        public void RefreshSerialPorts_Execute()
        {
            if (!string.IsNullOrEmpty(SelectedSerialPorts))
            {
                Global.SettingVM.SerialPortNum = SelectedSerialPorts;
                if (_lowTemperatureModule.Connect())
                {
                    //Global.LogHelper.WriteLog("RefreshSerialPorts_Execute-44");
                    // 连接成功，开始定时查询状态
                    Task.Run(() => StartPeriodicStatusCheck(_cancellationTokenSource.Token));
                }
                else
                {
                    _lowTemperatureModule = new LowTemperatureModule(SelectedSerialPorts);
                    if (_lowTemperatureModule.Connect())
                    {
                        //Global.LogHelper.WriteLog("RefreshSerialPorts_Execute-53");
                        // 连接成功，开始定时查询状态
                        Task.Run(() => StartPeriodicStatusCheck(_cancellationTokenSource.Token));
                    }
                }
                Global.MainVM.VersionText = "";
                Global.MainVM.SettingPageUrl = "./Pages/PrintChannelView.xaml";
            }
        }
        private async Task StartPeriodicStatusCheck(CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                string status = _lowTemperatureModule.GetStatus();
                string value = status.Split('=')[1];
                Global.LogHelper.WriteLog("查询实际温度回传:  " + value);
                // 使用Dispatcher更新UI
                Application.Current.Dispatcher.Invoke(() =>
                {
                    Global.MainViewVM.Temperature = value; 
                });
                await Task.Delay(1000, cancellationToken); 
            }
        }
        public void Cleanup()
        {
            _cancellationTokenSource.Cancel();
            _lowTemperatureModule.Disconnect();
        }

        public void InitializeChannels()
        {
            Configuration config = Global.config;
            var Source = Global.printProject.printChannels;
            channels = new List<ChannelViewModel>();

            var uniqueChannelTypes = Source
                .Select(channel => channel.ChannelType)
                .Where(type => !string.IsNullOrEmpty(type))
                .Distinct()
                .ToList();
            for (int i = 0; i < Source.Count; i++)
            {
                var channel = Source[i];
                var channelViewModel = new ChannelViewModel
                {
                    Name = "通道" + (i + 1),
                    Command = channel.ChannelID.ToString(),
                    SelectedCategory = channel.ChannelType,
                    Categories = uniqueChannelTypes
                };

                channels.Add(channelViewModel);
            }
        }
        public void SaveChannels()
        {
            string channelTypeStr = "";
            string channelNumListStr = "";
            for (int i = 0; i < channels.Count; i++)
            {
                var channel = channels[i];
                var printChannel = Global.printProject.printChannels[i];
                printChannel.ChannelID = int.Parse(channel.Command);
                printChannel.ChannelType = channel.SelectedCategory;
                channelTypeStr = String.Join(",", channels.Select(c => c.SelectedCategory));
                channelNumListStr = String.Join(",", channels.Select(c => c.Command));
                //if (i == channels.Count - 1)
                //{
                //    channelTypeStr += "调试通道";
                //    channelNumListStr += "1";
                //}
            }
            if (Global.config.AppSettings.Settings["ChannelTypes"] != null)
                Global.config.AppSettings.Settings["ChannelTypes"].Value = channelTypeStr;
            else
                Global.config.AppSettings.Settings.Add("ChannelTypes", channelTypeStr);
            if (Global.config.AppSettings.Settings["ChannelNumList"] != null)
                Global.config.AppSettings.Settings["ChannelNumList"].Value = channelNumListStr;
            else
                Global.config.AppSettings.Settings.Add("ChannelNumList", channelNumListStr);
            Global.config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
            Global.PrintChannelVM.SetHeader();
        }
        private string _name;
        private string _command;
        private string _selectedCategory;
        private bool _ControlEnabled = false;
        private string _SerialPortNum;
        public string SerialPortNum
        {
            //get
            //{   if(string.IsNullOrEmpty(_SerialPortNum))
            //        _SerialPortNum = Global.
            //    _SerialPortNum;
            //}
            get => _SerialPortNum;
            set => Set(ref _SerialPortNum, value);
        }
        public string Name
        {
            get => _name;
            set => Set(ref _name, value);
        }

        public string Command
        {
            get => _command;
            set => Set(ref _command, value);
        }

        public string SelectedCategory
        {
            get => _selectedCategory;
            set => Set(ref _selectedCategory, null);
        }
        public ObservableCollection<string> Categories { get; set; }
        public bool ControlEnabled
        {
            get => _ControlEnabled;
            set => Set(ref _ControlEnabled, value);
        }
        private ObservableCollection<string> _serialPorts;
        public ObservableCollection<string> SerialPorts
        {
            get => _serialPorts;
            set => Set(ref _serialPorts, value);
        }
        private string _selectedSerialPorts;
        public string SelectedSerialPorts
        {
            get => _selectedSerialPorts;
            set => Set(ref _selectedSerialPorts, value);
        }
    }
    public class ChannelViewModel
    {
        public string Name { get; set; }
        public string Command { get; set; }
        public string SelectedCategory { get; set; }
        public List<string> Categories { get; set; }

        public ChannelViewModel()
        {
            Categories = new List<string>();
        }
    }
}
